<template>
    <van-field v-model="code" :label="label" center clearable placeholder="请输入短信验证码">
        <template #button>
            <van-button size="small" type="info" :disabled="!!timer || isLoading" :loading="isLoading" @click="countDownAction" style="width:100px">{{showText}}</van-button>
        </template>
    </van-field>
</template>

<script>

const SEC = 60;

export default {

    props: ['smsCode', 'label', 'type'],
    inject: ['sendCode'],

    data() {
        return {
            code: "",
            timer: null,
            sec: 0,
            isLoading: false,
        }
    },

    destroyed() {
        clearInterval(this.timer);
        this.timer = null;
    },

    methods: {

        // 点击倒计时按钮
        countDownAction() {
            if (this.timer || this.isLoading) {
                return
            }
            this.isLoading = true;
            this.sendCode().then((ret) => {
                this.startCountDown(ret)
            })
        },

        // 开始倒计时
        startCountDown(sendFlag) {
            this.isLoading = false;
            if (sendFlag === false) {
                return;
            }
            this.sec = SEC;
            // 开始倒计时
            this.timer = setInterval(() => {
                this.sec--;
                if (this.sec == 0) {
                    this.resetStatus();
                }
            }, 1000);
        },

        // 重置样式
        resetStatus() {
            if (this.timer) {
                clearInterval(this.timer);
                this.timer = null
            }
            this.sec = SEC;
        },
    },

    computed: {

        // 格式化读秒显示
        formateSec() {
            if (this.sec >= 10) {
                return `${this.sec}`
            } else {
                return `0${this.sec}`
            }
        },

        // 整合界面显示文案
        showText() {
            if (this.timer) {
                return `还剩${this.formateSec}秒`
            } else {
                return "获取验证码"
            }
        }
    },

    watch: {
        code(value) {
            this.$emit("update:smsCode", value)
        }
    }
};
</script>

<style lang="scss" scoped>
.var_butt {
    width: 80px;
}
</style>
